package com.example.springboot.controller;

import com.example.springboot.constant.ResConstansts;
import com.example.springboot.entity.Res;
import com.example.springboot.entity.vo.PostVo;
import com.example.springboot.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/rankings")
public class RankingsController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private PostService postService;
    @GetMapping("/{type}")
    // "likes"、"views"、"collectCount"
    public Res<List<PostVo>> getRankingsOfLikes(@PathVariable String type) {
        try {
            List<PostVo> postVos = new ArrayList<>();
            Set<Object> rankings = redisTemplate.opsForZSet().reverseRange(type, 0, 100); // 获取前100名
            System.out.println("排行榜数据成功从redis获取");
            for (Object ranking : rankings) {
                PostVo data = (PostVo) getPostContent(ranking.toString());
                postVos.add(data);
            }
            return new Res<List<PostVo>>().code(200).data(postVos).msg("获取成功");
        } catch (Exception e) {
            try {
                System.out.println("redis获取失败，使用数据库获取");
                List<PostVo> postVos =postService.getRankingsByType(type);
                return new Res<List<PostVo>>().code(200).data(postVos).msg("获取成功");
            } catch (Exception ex) {
                return ResConstansts.SERVICE_ERROR;
            }
        }
    }

    public Object getPostContent(String postId) {
        // 根据 postId 获取具体内容
        return redisTemplate.opsForValue().get(postId);
    }
}
